import type { UserModule } from './types'
import { ViteSSG } from 'vite-ssg'
import ElementPlus from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { user } from '~/composables/useAuth'
import { createPinia } from 'pinia'
import { useAuthModalStore } from '~/stores/authModal' // 确保路径正确

zhCn.el.pagination.total = `共{total}项数据`
zhCn.el.pagination.goto = '跳至'

import { routes } from 'vue-router/auto-routes'
import App from './App.vue'
import '~/styles/index.scss'
import 'uno.css'

const protectedRoutes = [
    // '/search',
    // '/search/MicrobialSearch',
    // '/search/FungiSearch',
    // '/identification',
    // '/identification/identification/MicrobialIdentification',
    // '/identification/FungiIdentification'
]

export const createApp = ViteSSG(
    App,
    {
        routes,
        base: import.meta.env.BASE_URL,
    },
    (ctx) => {
        // 添加 Pinia
        const pinia = createPinia()
        ctx.app.use(pinia)

        // 在路由守卫中使用 store
        ctx.router.beforeEach((to) => {
            if (to.path === '/' || to.path === '/Login') {
                return true
            }

            const requiresAuth = protectedRoutes.some(prefix =>
                to.path === prefix || to.path.startsWith(prefix + '/')
            )

            if (requiresAuth && !user.value) {
                // 在路由守卫内部获取 store
                const authModal = useAuthModalStore()
                authModal.setRouter(ctx.router)
                authModal.showModal(to.fullPath)
                return false
            }
            return true
        })

        ctx.app.use(ElementPlus, { locale: zhCn })

        Object.values(import.meta.glob<{ install: UserModule }>('./modules/*.ts', { eager: true }))
            .forEach(i => i.install?.(ctx))
    }
)